﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

using SYcwpb.Helpers;

namespace SYcwpb.WinForm
{
    public partial class AssignTables : Form
    {
        private string strline;

        private int nowday = 0;
        private int startweek = 0;

        private ToolStripMenuItem[] menuitems;
        private System.Windows.Forms.Label[] labels;

        private SqlDataLayer sqlHelper = new SqlDataLayer();
        private Dictionary<string, int> DicTableNameToID = new Dictionary<string, int>();

        private static AssignTables _assignTables = null;

        public Action UpdateMainViewTimeTableAction = null;

        private AssignTables()
        {
            strline = CONSTDATA.UserModel.Line;
            // 加载菜单项
            int menucount=0;
            string strsql = "select ti.* from TableInfo as ti where ti.LineID='" + strline + "' and exists (select cr.id from CrossingRoad as cr where cr.tableinfo_id=ti.id)";

            DataTable tempdt = null;
            try
            {
                tempdt = sqlHelper.SelectDt(strsql);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("查找时刻表安排出现故障");
            }
           
            if (tempdt != null && tempdt.Rows.Count > 0)
            {
                List<string> list = new List<string>();
                list.Add("P表");
                list.Add("S表");
                list.Add("J表");
                list.Add("未分配");
                menucount = tempdt.Rows.Count;
                menuitems = new ToolStripMenuItem[4];
                for (int i = 0; i < list.Count; i++)
                {
                    menuitems[i] = new ToolStripMenuItem();
                    menuitems[i].Name = list[i];
                    menuitems[i].Text = list[i];
                    menuitems[i].Size = new System.Drawing.Size(124, 22);
                    DataRow[] rows = tempdt.Select("TableClass='" + i + "'");
                    foreach (DataRow row in rows)
                    {
                        string name = row["TableName"].ToString();
                        int ID = Convert.ToInt32(row["ID"]);
                        menuitems[i].DropDownItems.Add(name, null, new System.EventHandler(this.MenuItemSet_Click));
                        if (!DicTableNameToID.ContainsKey(name))
                        {
                            DicTableNameToID.Add(name, ID);
                        }
                    }
                }
                //menuitems = new ToolStripMenuItem[menucount];
                //for (int i = 0; i < menucount; i++)
                //{
                //    string name = tempdt.Rows[i]["TableName"].ToString();
                //    int ID = Convert.ToInt32(tempdt.Rows[i]["ID"]);

                //    menuitems[i] = new ToolStripMenuItem();
                //    menuitems[i].Name = name;
                //    menuitems[i].Text = menuitems[i].Name;
                //    menuitems[i].Size = new System.Drawing.Size(124, 22);
                //    menuitems[i].Click += new System.EventHandler(this.MenuItemSet_Click);
                //    menuitems[i].DropDownItems.Add("ceshi");

                //    if (!DicTableNameToID.ContainsKey(name))
                //    {
                //        DicTableNameToID.Add(name, ID);
                //    }
                //}
            }
            else
            {
                menucount = 0;
                menuitems = new ToolStripMenuItem[1];

                menuitems[0] = new ToolStripMenuItem();
                menuitems[0].Name = "NoTableExist";
                menuitems[0].Text = menuitems[0].Name;
                menuitems[0].Size = new System.Drawing.Size(124, 22);
                menuitems[0].Click += new System.EventHandler(this.MenuItemSet_Click);
            }

            InitializeComponent();

            contextMenuStrip1.Items.AddRange(menuitems);
        }

        public static AssignTables GetInstances()
        {
            if (null == _assignTables || _assignTables.IsDisposed)
                _assignTables = new AssignTables();

            return _assignTables;
        }

        private void MenuItemSet_Click(object sender,EventArgs e)
        {
            string tbname=((ToolStripMenuItem)sender).Text;
            int ID;
            if (!DicTableNameToID.TryGetValue(tbname, out ID)){
                return;}

            int result = -1; //0 表示不能更新，1表示可以更新

            try
            {
                foreach (ListViewItem lvi in lv_TbToDate.SelectedItems)
                {
                    if (lvi.Index >= startweek + nowday - 1)//进行设置
                    {
                        if (!UpdateTableToDate(lvi, ID,ref result))
                        {
                            if (result == 0)
                            {
                                MessageBoxHelper.ShowError("无法对历史日期进行更新，请确认！");
                            }
                            else
                                MessageBoxHelper.ShowError("设置时刻表安排时出现故障！");

                            continue;
                        }

                        if (result == 1)
                        {
                            string date = lvi.Text.Substring(0, lvi.Text.IndexOf("\r"));

                            lvi.Text = date + "\r" + tbname;

                            //如果更新的是今天的时刻表，主界面今日使用时刻表处作更新

                            if (date == DateTime.Today.ToString("yyyy-MM-dd"))
                            {
                                UpdateMainViewTimeTableAction();
                            }
                        }
                    }
                }
                foreach (ListViewItem lvi in lv_week.SelectedItems)
                {
                    if (!UpdateTableToDate(lvi, ID,ref result))
                    {
                        MessageBoxHelper.ShowError("设置时刻表安排时出现故障！");

                        continue;
                    }

                    if (result == 1)
                        lvi.Text = lvi.Text.Substring(0, lvi.Text.IndexOf("\r")) + "\r" + tbname;
                }
            }
            catch(System.Exception ex)
            {
                MessageBoxHelper.ShowError("设置时刻表安排时出现故障！");
            }
            
            lv_TbToDate.ContextMenuStrip = null;
            //UpdateListView1();
        }

        private bool UpdateTableToDate(ListViewItem lvi, int tableID,ref int result)
        {
            string mydate = lvi.SubItems[0].Text.Substring(0, 10);

            string today = DateTime.Now.ToString("yyyy-MM-dd");

            if (today.CompareTo(mydate) > 0)
            {
                result = 0;
                return false;
            }

            string isExiststr = "select A.ID,A.AssignDate,B.TableName from TableTodate A left join TableInfo B on A.TableInfo_id = B.ID where B.LineID = '" + strline + 
                "' and A.AssignDate = '" + mydate + "'";

            DataTable dt = sqlHelper.SelectDt(isExiststr);
            if (dt != null)
            {
                if (dt.Rows.Count == 1)
                {
                    string updateStr = "update TableToDate set TableInfo_id ='" + tableID + "' where ID ='" + dt.Rows[0]["ID"] + "'";
                    sqlHelper.ExecuteSql(updateStr);


                    result = 1;
                }
                else if (dt.Rows.Count > 1)
                {
                    result = 0;

                    return false;
                }
                else
                {
                    string insertStr = "insert TableToDate (AssignDate,TableInfo_id,MilesAdded) values ('" + mydate + "','" + tableID + "',0)";
                    sqlHelper.ExecuteSql(insertStr);

                    result = 1;
                }

                return true;
            }
            else
                return false;
        }

        private void UpdateListView1()
        {
            InitView(0);
            InitView(1);
        }

        /// <summary>
        /// 初始化月表，
        /// </summary>
        /// <param name="mon">表示这个月，还是下个月</param>
        private void InitView(int mon)
        {
            ListView view ;
            DateTime startMonth;  //每个月的一号

            if (mon == 0) //本月
            {
                view = this.lv_TbToDate;
                startMonth = DateTime.Now.AddDays(1 - DateTime.Now.Day);  // 本月一号
            }
            else //下个月
            {
                view = this.lv_week;
                startMonth = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-01")).AddMonths(1);  //下个月一号
            }

            int startWeek = Convert.ToInt32(startMonth.DayOfWeek) % 7 ;

            DateTime endOfMonth = startMonth.AddMonths(1).AddDays(-1);
            TimeSpan tSpan = endOfMonth - startMonth;
            int totalDaysOfMonth = tSpan.Days + 1;  //当月总共有多少天

            view.Items.Clear();
            imageList2.Images.Clear();

            for (int i = 0; i < startWeek; i++)
            {//加载空的
                ListViewItem lvi = new ListViewItem("", i);
                view.Items.Add(lvi);
            }

            DateTime currTime = startMonth;
            DateTime now = DateTime.Now;
            for (int i = 0; i < totalDaysOfMonth; i ++ )
            {
                string shows;
                shows = currTime.ToString("yyyy-MM-dd");
                string tempstr = sqlHelper.SelectTableToDate(shows, strline);
                if (tempstr != "")
                {
                    shows += "\r";
                    shows = shows + tempstr;
                }
                else
                {
                    shows += "\r";
                    shows += "未设置";
                }
                ListViewItem lvi = new ListViewItem(shows, i + startweek);
                view.Items.Add(lvi);

                int result = currTime.ToString("yyyy-MM-dd").CompareTo(now.ToString("yyyy-MM-dd"));

                if (result < 0)
                    view.Items[i + startWeek].BackColor = Color.FromArgb(168, 168, 168);
                else if (result == 0)
                    view.Items[i + startWeek].BackColor = Color.FromArgb(175,238,238);
                else
                    view.Items[i + startWeek].BackColor = Color.FromArgb(240, 240, 240);

                currTime = currTime.AddDays(1);
            }

        }

        private void InitDefaultComboBox()
        {
            if (null == DicTableNameToID)
                return;

            foreach (string key in DicTableNameToID.Keys)
            {
                cbb_curday.Items.Add(key);
                cbb_curken.Items.Add(key);
                cbb_nextday.Items.Add(key);
                cbb_nextken.Items.Add(key);
            }
        }

        private void AssignTables_Load(object sender, EventArgs e)
        {
            UpdateListView1();

            InitDefaultComboBox();
        }



        private void lv_TbToDate_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button==MouseButtons.Right)
            {
                if (lv_TbToDate.SelectedItems.Count>0)//应该是判断是否被选择的都是未来的日期
                {
                    lv_TbToDate.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }

        private void lv_week_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (lv_week.SelectedItems.Count > 0)//应该是判断是否被选择的都是未来的日期
                {
                    lv_week.ContextMenuStrip = contextMenuStrip1;
                }
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedIndex==0)
            {
                this.lv_week.SelectedItems.Clear();
            } 
            else
            {
                this.lv_TbToDate.SelectedItems.Clear();
            }
        }

        private void btn_default_Click(object sender, EventArgs e)
        {
            Button btn = sender as Button;

            if (null == btn)
                return;

            DateTime dt_first_day = DateTime.Now.AddDays(1 - DateTime.Now.Day);  // 本月一号
            string tbname = "";
            bool isSetDay = true;


            switch (btn.Name)
            {
                case "btn_curday":
                    dt_first_day = DateTime.Now.AddDays(1);  //从当前日期的下一天起可以进行默认更新
                    if (cbb_curday.SelectedItem == null)
                    {
                        MessageBoxHelper.ShowError("请选择需要设置的时刻表后重试！");
                        return;
                    }
                    if (dt_first_day.Month > DateTime.Now.Month)
                    {
                        MessageBoxHelper.ShowTips("没有可以设置默认时刻表的日期！");
                        return;
                    }
                    tbname = cbb_curday.SelectedItem.ToString();
                    break;
                case "btn_curken":
                    if (cbb_curken.SelectedItem == null)
                    {
                        MessageBoxHelper.ShowError("请选择需要设置的时刻表后重试！");
                        return;
                    }
                    dt_first_day = DateTime.Now.AddDays(1);  //从当前日期的下一天起可以进行默认更新
                    if (dt_first_day.Month > DateTime.Now.Month)
                    {
                        MessageBoxHelper.ShowTips("没有可以设置默认时刻表的日期！");
                        return;
                    }
                    tbname = cbb_curken.SelectedItem.ToString();
                    isSetDay = false;
                    break;
                case "btn_nextday":
                    if (cbb_nextday.SelectedItem == null)
                    {
                        MessageBoxHelper.ShowError("请选择需要设置的时刻表后重试！");
                        return;
                    }
                    tbname = cbb_nextday.SelectedItem.ToString();
                    dt_first_day = dt_first_day.AddMonths(1);
                    break;
                case "btn_nextken":
                    if (cbb_nextken.SelectedItem == null)
                    {
                        MessageBoxHelper.ShowError("请选择需要设置的时刻表后重试！");
                        return;
                    }
                    tbname = cbb_nextken.SelectedItem.ToString();
                    dt_first_day = dt_first_day.AddMonths(1);
                    isSetDay = false;
                    break;
                default:
                    break;
            }

            if (string.IsNullOrEmpty(tbname))
            {
                MessageBoxHelper.ShowError("请选择需要设置的时刻表后重试！");
                return;
            }

            SetDafaultTable(tbname,isSetDay, dt_first_day);

        }

        private void SetDafaultTable(string tbName,bool isSetDay,DateTime dt_first_day)
        {
            int tbID ;
            if (!DicTableNameToID.TryGetValue(tbName, out tbID))
            {
                MessageBoxHelper.ShowError("获取时刻表信息失败，请确认时刻表存在后重试！");
                return;
            }

            DateTime _1stDay = new DateTime(dt_first_day.Year,dt_first_day.Month,1);
            DateTime endOfMonth = _1stDay.AddMonths(1).AddDays(-1);

            TimeSpan tSpan = endOfMonth - dt_first_day;
            int totalDaysOfMonth = tSpan.Days + 1;  //当月总共有多少天

            DateTime curTime = dt_first_day;

            List<string> SetDaysList = new List<string>();

            bool isAdded = false;

            for (int i = 0; i <= totalDaysOfMonth; i ++ )
            {
                if (isSetDay)
                {
                    if (
                           curTime.DayOfWeek == DayOfWeek.Monday
                        || curTime.DayOfWeek == DayOfWeek.Tuesday
                        || curTime.DayOfWeek == DayOfWeek.Wednesday
                        || curTime.DayOfWeek == DayOfWeek.Thursday
                        || curTime.DayOfWeek == DayOfWeek.Friday
                        )
                    {
                        isAdded = true;
                    }
                }
                else
                {
                    if (curTime.DayOfWeek == DayOfWeek.Saturday|| curTime.DayOfWeek == DayOfWeek.Sunday)
                        isAdded = true;
                }

                if (isAdded)
                    SetDaysList.Add(curTime.ToString("yyyy-MM-dd"));

                isAdded = false;
                curTime = curTime.AddDays(1);
            }

            SetDefaultTableToDB(SetDaysList, tbID);

        }

        private void SetDefaultTableToDB(List<string> SetDaysList, int tableID)
        {
            if (null == SetDaysList || SetDaysList.Count < 1)
                return;

            ArrayList insertList = new ArrayList();

            foreach(string day in SetDaysList)
            {
                string isExiststr = "select A.ID,A.AssignDate,B.TableName from TableTodate A left join TableInfo B on A.TableInfo_id = B.ID where B.LineID = '" + strline +
                                    "' and A.AssignDate = '" + day + "'";

                DataTable dt = sqlHelper.SelectDt(isExiststr);

                if (null != dt)
                {
                    if (dt.Rows.Count == 0)//没有设置的日期进行设置
                    {
                        insertList.Add("insert TableToDate (AssignDate,TableInfo_id,MilesAdded) values ('" + day + "','" + tableID + "',0)");
                    }
                    else if (dt.Rows.Count == 1)//已经设置过的进行更新
                    {
                        insertList.Add("update TableToDate set TableInfo_id ='" + tableID + "' where ID ='" + dt.Rows[0]["ID"] + "'");
                    }
                    else
                        continue;
                }
            }

            if (insertList.Count > 0)
            {
                if (sqlHelper.ExecuteSqlTran(insertList))
                {
                    MessageBoxHelper.ShowTips("设置默认时刻表操作已完成！");
                    UpdateListView1(); 
                }
            }
            else
            {
                MessageBoxHelper.ShowTips("没有可以设置默认时刻表的日期！");
            }
        }
    }
}
